import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { POPUP_AD_DIALOG } from '@/constant'

const adConfigList = []
let configIndex = -1

export const useAdDialogStore = defineStore('ad-dialog', () => {
  const type = ref(null)

  const isOpen = computed(() => type.value !== null)

  function $openAdDialog(type, options = {}) {
    addConfig({
      type,
      ...options,
    })
    return { next: $openAdDialog, open: openNext }
  }

  function close() {
    if (adConfigList.length <= 0) throw new Error(`[useAdDialogStore] Do not call close() when adConfigList is empty`)
    type.value = null
    adConfigList.splice(0, adConfigList.length)
    configIndex = -1
  }

  function addConfig({ type }) {
    adConfigList.push({ type })
  }

  function openNext() {
    configIndex += 1
    const config = adConfigList[configIndex]
    if (config) {
      setRefs(config)
    } else {
      throw new Error(`[useAdDialogStore] openNext config is null`)
    }
  }

  function setRefs({ type: typeOpt }) {
    type.value = typeOpt
  }

  // url query premiym 為 1 就自動打開
  const premium = new URL(window.location.href).searchParams.get('premium')
  if (premium === '1') {
    $openAdDialog(POPUP_AD_DIALOG.PREMIUM).open()
  }

  return {
    type,
    isOpen,
    $openAdDialog,
    close,
  }
})
